<?php

namespace App\Http\Controllers\Frontend\Hr;

use Auth;
use App\Models\Hr;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Requests\Hr\SignupRequest;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller {

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    public function signup(SignupRequest $request)
    {
        $mobile = $request->get('mobile');
        $password = $request->get('password');

        $hr = Hr::create([
           'mobile' => $mobile,
           'email' => $mobile . '@wxx.im',
           'password' => bcrypt($password),
        ]);

        $role = Role::ofHr()->first();
        $hr->roles()->attach($role->id);

        Auth::attempt(['email' => $hr->email, 'password' => $password]);

        return ['success' => ['redirect' => url('/hr')]];
    }

    public function signin(Request $request)
    {
        $mobile = $request->input('mobile');
        $password = $request->input('password');
        $remember = $request->input('remember', 0);

        // 频繁登陆处理
        $throttles = $this->isUsingThrottlesLoginsTrait();
        if($throttles && $this->hasTooManyLoginAttempts($request)) {
            $seconds = $this->secondsRemainingOnLockout($request);
            return response(['error' => ['field' => 'password', 'message' => $this->getLockoutErrorMessage($seconds)]], 422);
        }

        if (Auth::attempt(['email' => $mobile . '@wxx.im', 'password' => $password], $remember)) {
            return ['success' => ['redirect' => url('/hr')]];
        } else {
            if ($throttles)
                $this->incrementLoginAttempts($request);
            return response(['error' => ['field' => 'password', 'message' => '手机号码或者密码不正确']], 422);
        }
    }

    public function signout()
    {
        Auth::logout();
        return redirect('/')->withInfo('您已经安全退出登陆');
    }
}
